package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.dto.SetmealDto;
import com.itheima.reggie.mapper.SetmealMapper;
import com.itheima.reggie.pojo.Setmeal;
import com.itheima.reggie.pojo.SetmealDish;
import com.itheima.reggie.service.SetmealDishService;
import com.itheima.reggie.service.SetmealService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.DeleteMapping;

import java.util.List;
import java.util.Set;

@Service
@Transactional
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {
    @Autowired
    private SetmealDishService setmealDishService;

    /**
     * 添加套餐
     * @param setmealDto
     */
    @Override
    public void saveWithDish(SetmealDto setmealDto) {
        //    1.保存套餐表数据 setmeal
        this.save(setmealDto);

        //    2.保存套餐关系数据 seatmeal_dish
        List<SetmealDish> setmealDishList = setmealDto.getSetmealDishes();
        //遍历设置每一个setmealDish的setmealId值(保存了套餐ID，前台会发送菜品ID)
        setmealDishList.forEach(setmealDish -> setmealDish.setSetmealId(setmealDto.getId()));
        setmealDishService.saveBatch(setmealDishList);
    }

    /**
     * 批量删除带菜品联系表
     * @param
     */
    @Override
    @Transactional
    public void removeWithDish(List<Long> ids) {
    //    0.判断套餐是否正在售卖 select count(*) from setmeal where id in (ids) and status=1
        QueryWrapper<Setmeal> queryWrapper1=new QueryWrapper<>();
        queryWrapper1.in(ids.size()>0,"id",ids);
        queryWrapper1.eq("status",1);
        int count = this.count(queryWrapper1);
        if(count>0){
            throw new CustomException("套餐正在售卖，无法删除");
        }
        //    1.删除套餐 delete from setmeal where id in ids
        this.removeByIds(ids);
    //    2.删除套餐菜品数据 delete from setmeal_dish where setmeal_id in ids
        QueryWrapper<SetmealDish> queryWrapper2=new QueryWrapper<>();
        queryWrapper2.in("setmeal_id",ids);
        setmealDishService.remove(queryWrapper2);
    }




}